<?php

namespace app\api\controller;

use app\api\controller\User as ControllerUser;
use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use app\common\model\User;
use think\Hook;
use think\Db;

class Service extends Api
{
    protected $noNeedLogin = ["getServiceLists","getServiceDetail"];
    protected $noNeedRight = '*';
 
    //服务列表
    public function getServiceLists()
    {
        $lang = $this->request->post("lang", 1);
        $page = $this->request->post("page", 1);
        $limit = $this->request->post("limit", 10);

        //区分语言
        if($lang == 1){
            $field = "
            id, 
            service_name, 
            service_banner, 
            service_tags, 
            service_score,
            service_logo,
            service_characteristic";
        }else{
            $field = "
            id, 
            service_name_hk as service_name, 
            service_banner, 
            service_tags_hk as service_tags, 
            service_score,
            service_logo,
            service_characteristic";
        }

        $lists = Db::name("service")
        ->field($field)
        ->page($page, $limit)
        ->order("sort desc")
        ->select();

        $url = Db::name("config")->where(['name' => 'url'])->value('value');

        //处理数据
        foreach($lists as &$value){
            $value["service_tags"] = explode(",", $value["service_tags"]);
            $value["service_characteristic"] = json_decode($value["service_characteristic"], true);
            if($value["service_banner"]){
                $value["service_banner"] = $url . $value["service_banner"];
            }
            if($value["service_logo"]){
                $value["service_logo"] = $url . $value["service_logo"];
            }
            
        }

        $this->success("操作成功", $lists);

    }

    //服务详情
    public function getServiceDetail()
    {
        $id = $this->request->post("id");
        $lang = $this->request->post("lang", 1);

        if(!$id){
            $this->error("参数错误");
        }

        //区分语言
        if($lang == 1){
            $field = "
            id, 
            service_name, 
            service_banner, 
            service_tags, 
            service_score, 
            price,
            people_num,
            `desc`, 
            service_where, 
            flow_image, 
            material,
            content,
            service_characteristic,
            customer_qrcode_img";
        }else{
            $field = "
            id, 
            service_name_hk as service_name, 
            service_banner, 
            service_tags_hk as service_tags, 
            service_score,
            price,
            people_num,
            desc_hk as `desc`, 
            service_where_hk as service_where, 
            flow_image, 
            material_hk as material,
            content,
            service_characteristic,
            customer_qrcode_img";
        }
        $info = Db::name("service")
            ->field($field)
            ->where("id = " . $id)
            ->find();

        //处理数据
        $info["service_tags"] = explode(",", $info["service_tags"]);

        $url = Db::name("config")->where(['name' => 'url'])->value('value');

        if($info["customer_qrcode_img"]){
            $info["customer_qrcode_img"] = $url . $info["customer_qrcode_img"];
        }

        // $info["service_where"] = array_values(json_decode($info["service_where"], true));
        
        // $info["material"] = array_values(json_decode($info["material"], true));

        $info["content"] = json_decode($info["content"], true) ?? [];

        foreach($info["content"] as $k => $v){
            $info["content"][$k]["id"] = $k + 1;
        }

        $info["service_characteristic"] = json_decode($info["service_characteristic"], true) ?? [];

        $this->success("操作成功", $info);

    }

    //获取服务对应的调查问卷
    public function getServiceQuestionAnswer()
    {
        $service_id = $this->request->post("service_id");
        if(empty($service_id)){
            $this->error("缺少必要参数服务id");
        }

        //关联问卷表
        $question_answer_info = Db::name("service")
        ->alias("s")
        ->field("qa.*")
        ->join("question_answer qa", "s.question_answer_id = qa.id", "left")
        ->where("s.id = " . $service_id)
        ->find();

        if(!$question_answer_info){
            $this->error("暂无问卷");
        }

        $question_answer_info["question_answer"] = json_decode($question_answer_info["question_answer"], true);

        $this->success("获取成功", $question_answer_info);
        
    }

    //所有申请服务，整合一个方法
    public function applyService()
    {
        $service_id = $this->request->post("service_id");
        $question_answer_id = $this->request->post("question_answer_id");
        $question_answer_info = $this->request->post("question_answer_info");
        $name = $this->request->post("name");

        //验证数据不能为空
        if(empty($service_id) || empty($question_answer_id) || empty($question_answer_info) || empty($name)){
            $this->error("必要参数缺少");
        }

        $question_answer_info = $this->htmlToJson($question_answer_info);

        $user = $this->auth->getUser() ?? [];

        $service_info = Db::name("service")
        ->where("id = " . $service_id)
        ->find();

        //插入数据
        Db::name("service_apply")
        ->insert([
            "uid" => $user->id,
            "service_id" => $service_id,
            "service_name" => $service_info["service_name"],
            "question_answer_id" => $question_answer_id,
            "question_answer_json" => $question_answer_info,
            "name" => $name,
            "createtime" => time()
        ]);

        $id = Db::name("service_company_apply")->getLastInsID();
        //插入订单表
        $params = [
            "service_id" => $service_id,
            "uid" => $user->id,
            "apply_name" => $service_info["service_name"]
        ];
        $this->addServiceOrder($id, $params);

        $this->success("申请成功，请等待审核");
    }

    //申请服务 旧
    public function applyServiceCopy()
    {
        $service_id = $this->request->post("service_id");
        if(empty($service_id)){
            $this->error("缺少必要参数服务id");
        }

        //1香港移民 2香港留学 3企业补贴 4开办企业
        if($service_id == 1){ 
            $this->applyMigrate();
        }else if($service_id == 2){
            $this->applyAbroad();
        }else if($service_id == 3){
            $this->applyCompany();
        }else if($service_id == 4){
            $this->applyStartBusiness();
        }
    }

    //申请服务 留学类
    public function applyAbroad()
    {
        $service_id = $this->request->post("service_id");
        $name = $this->request->post("name");
        $sex = $this->request->post("sex"); //1男   2女
        $birthday = $this->request->post("birthday");
        $identity_id = $this->request->post("identity_id");
        $identity_name = $this->request->post("identity_name");

        //学历信息 education_json
        $education_json = $this->request->post("education_json", "");
        $education_json = $this->htmlToJson($education_json);
        

        //学术成绩 处理成science_json
        $science_json = [];
        $science_json["collegeExamination"] = $this->request->post("collegeExamination", "");//内地高考
        $science_json["ibdp"] = $this->request->post("ibdp", "");
        $science_json["hkdse"] = $this->request->post("hkdse", "");
        $science_json["ial"] = $this->request->post("ial", "");
        $science_json["study_other"] = $this->request->post("study_other", "");//学术其他
        $science_json = json_encode($science_json, JSON_UNESCAPED_UNICODE);

        //英语能力 处理成english_json
        $english_json = [];
        $english_json["collegeEnglish"] = $this->request->post("collegeEnglish", "");//高考英语成绩
        $english_json["englishSix"] = $this->request->post("englishSix", "");//英语6级
        $english_json["englishFour"] = $this->request->post("englishFour", "");//英语4级
        $english_json["ielts"] = $this->request->post("ielts", "");//雅思
        $english_json["toelf"] = $this->request->post("toelf", "");//托福
        $english_json = json_encode($english_json, JSON_UNESCAPED_UNICODE);

        //国际课程 处理成international_json
        $international_json = [];
        $international_json["ibEnglishGrade"] = $this->request->post("ibEnglishGrade", "");
        $international_json["igcseEnglishGrade"] = $this->request->post("igcseEnglishGrade", "");
        $international_json["gceEnglish"] = $this->request->post("gceEnglish", "");
        $international_json["hkdseEnglish"] = $this->request->post("hkdseEnglish", "");
        $international_json["inter_other"] = $this->request->post("inter_other", "");
        $international_json = json_encode($international_json, JSON_UNESCAPED_UNICODE);

        //报读志愿
        $apply_intention_school = $this->request->post("apply_intention_school", "");//申请意向院校
        $read_type_id = $this->request->post("read_type_id", ""); //修读方式id
        $read_type_name = $this->request->post("read_type_name", ""); //修读方式名称
        $proposed_education_id = $this->request->post("proposed_education_id", ""); // 拟报学历id 
        $proposed_education_name = $this->request->post("proposed_education_name", ""); // 拟报学历名称
        $read_other = $this->request->post("read_other", ""); //报读支援其他要求

        //其他补充
        $speciality_approve = $this->request->post("speciality_approve", ""); //专业认可
        $work_experience = $this->request->post("work_experience", ""); //工作经验
        $achieve = $this->request->post("achieve", ""); //奖励/成就

        $user = $this->auth->getUser();

        //验证数据不能为空
        if(empty($service_id)){
            $this->error("必要参数缺少");
        }
        if(empty($name)){
            $this->error("请填写姓名");
        }
        if(empty($sex)){
            $this->error("请选择性别");
        }
        if(empty($birthday)){
            $this->error("请输入生日");
        }
        if(empty($identity_id)){
            $this->error("请选择申请人身份");
        }
        //插入数据
        Db::name("service_abroad_apply")
        ->insert([
            "uid" => $user->id,
            "service_id" => $service_id,
            "name" => $name,
            "sex" => $sex,
            "birthday" => $birthday,
            "identity_id" => $identity_id,
            "identity_name" => $identity_name,
            "education_json" => $education_json,
            "science_json" => $science_json,
            "english_json" => $english_json,
            "international_json" => $international_json,
            "apply_intention_school" => $apply_intention_school,
            "read_type_id" => $read_type_id,
            "read_type_name" => $read_type_name,
            "proposed_education_id" => $proposed_education_id,
            "proposed_education_name" => $proposed_education_name,
            "read_other" => $read_other,
            "speciality_approve" => $speciality_approve,
            "work_experience" => $work_experience,
            "achieve" => $achieve,
            "createtime" => time()
        ]);

        $id = Db::name("service_abroad_apply")->getLastInsID();

        //插入订单表
        $params = [
            "service_id" => $service_id,
            "uid" => $user->id,
            "apply_name" => "abroad"
        ];
        $this->addServiceOrder($id, $params);

        $this->success("申请成功，请等待审核");
    }

    //html符号转义为json
    public function htmlToJson($string)
    {
        $string = str_replace("&quot;", '"', $string);
        return $string;
    }

    //插入订单
    public function addServiceOrder($id, $params)
    {
        //生成订单编号
        $order_no = date("YmdHis") . rand(1,99999);

        //查询下单人的上级销售/代理商/分公司
        $ControllerUser = new ControllerUser();
        $saleAgentBranch_info = $ControllerUser->getSaleAgentBranch($params["uid"]);

        //查询服务基础数信息
        $service_info = Db::name("service")
        ->where("id = " . $params["service_id"])
        ->find();
        
        Db::name("service_order")
        ->insert(
            [
                "service_id" => $params["service_id"],
                "service_img" => $service_info["service_banner"],
                "order_no" => $order_no,
                "apply_id" => $id,
                "apply_name" => $params["apply_name"], //服务名称
                "uid" => $params["uid"],
                "status" => 0,
                "branch_office_uid" => $saleAgentBranch_info["branch_office_uid"], //分公司id
                "agent_uid" => $saleAgentBranch_info["agent_uid"],//代理商id
                "sale_uid" => $saleAgentBranch_info["sale_uid"],//销售id
                "createtime" => time()
            ]
        );

        $order_id = Db::name("service_order")->getLastInsID();

        //回填订单编号
        Db::name("service_apply")
        ->where("id = " . $id)
        ->update(["order_id" => $order_id, "order_no" => $order_no]);

        return true;
    }

    //获取身份列表
    public function getIdentityLists()
    {
        $lang = $this->request->post("lang", 1);
        if($lang == 1){
            $field = "id, name";
        }else{
            $field = "id, name_hk as name";
        }
        $lists = Db::name("identity")
        ->field($field)
        ->select();

        $this->success("操作成功", $lists);
    }

    //获取修读方式列表
    public function getReadTypeLists()
    {
        $lang = $this->request->post("lang", 1);
        if($lang == 1){
            $field = "id, name";
        }else{
            $field = "id, name_hk as name";
        }
        $lists = Db::name("read_type")
        ->field($field)
        ->select();

        $this->success("操作成功", $lists);
    }

    //获取拟报学历列表
    public function getProEduLists()
    {
        $lang = $this->request->post("lang", 1);
        if($lang == 1){
            $field = "id, name";
        }else{
            $field = "id, name_hk as name";
        }
        $lists = Db::name("proposed_education")
        ->field($field)
        ->select();

        $this->success("操作成功", $lists);
    }

    //申请企业补贴
    public function applyCompany()
    {
        $service_id = $this->request->post("service_id");
        $reg_name = $this->request->post("reg_name"); //企业名称
        $reg_type_id = $this->request->post("reg_type_id");  //公司性质id
        $reg_type_name = $this->request->post("reg_type_name"); //公司性质名称
        $reg_create_date = $this->request->post("reg_create_date"); //公司成立日期
        $is_have_office = $this->request->post("is_have_office"); //是否有办公室 0无 1有
        $staff_num = $this->request->post("staff_num"); //员工数量
        $is_have_mpf = $this->request->post("is_have_mpf"); //是否为员工购买MPF（养老金） 0无 1有
        $last_year_turnover = $this->request->post("last_year_turnover"); //上年度营业额
        $is_have_new_plan = $this->request->post("is_have_new_plan"); //可否提供最新计划报告 0否 1可
        $industry_id = $this->request->post("industry_id"); //所属行业id
        $industry_name = $this->request->post("industry_name"); //所属行业名称
        $goods_from_country = $this->request->post("goods_from_country"); //产品来源以及销售地区/国家
        $goods_name = $this->request->post("goods_name"); //产品名称
        $sale_type = $this->request->post("sale_type"); //销售方式
        $ownership_company_json = $this->request->post("ownership_company_json"); //公司股权结构
        $ownership_company_json = $this->htmlToJson($ownership_company_json);
        $ownership_target_json = $this->request->post("ownership_target_json"); //目标地区/国家公司
        $ownership_target_json = $this->htmlToJson($ownership_target_json);
        $target_country = $this->request->post("target_country"); //目标地区/国家
        $target_is_have_company = $this->request->post("target_is_have_company"); //目标地区是否已成立公司 0无 1有
        $plan_to_fund_id = $this->request->post("plan_to_fund_id"); //计划使用基金范围id
        $plan_to_fund_name = $this->request->post("plan_to_fund_name"); //计划使用基金范围

        //验证数据不能为空
        if(empty($service_id)){
            $this->error("必要参数缺少");
        }

        $user = $this->auth->getUser();

        //插入数据
        Db::name("service_company_apply")
        ->insert([
            "uid" => $user->id,
            "service_id" => $service_id,
            "reg_name" => $reg_name,
            "reg_type_id" => $reg_type_id,
            "reg_type_name" => $reg_type_name,
            "reg_create_date" => $reg_create_date,
            "is_have_office" => $is_have_office,
            "staff_num" => $staff_num,
            "is_have_mpf" => $is_have_mpf,
            "last_year_turnover" => $last_year_turnover,
            "is_have_new_plan" => $is_have_new_plan,
            "industry_id" => $industry_id,
            "industry_name" => $industry_name,
            "goods_from_country" => $goods_from_country,
            "goods_name" => $goods_name,
            "sale_type" => $sale_type,
            "ownership_company_json" => $ownership_company_json,
            "ownership_target_json" => $ownership_target_json,
            "target_country" => $target_country,
            "target_is_have_company" => $target_is_have_company,
            "plan_to_fund_id" => $plan_to_fund_id,
            "plan_to_fund_name" => $plan_to_fund_name,
            "createtime" => time()
        ]);

        $id = Db::name("service_company_apply")->getLastInsID();
        //插入订单表
        $params = [
            "service_id" => $service_id,
            "uid" => $user->id,
            "apply_name" => "company"
        ];
        $this->addServiceOrder($id, $params);

        $this->success("申请成功，请等待审核");

    }

    //获取公司性质列表
    public function getRegTypeLists()
    {
        $lang = $this->request->post("lang", 1);
        if($lang == 1){
            $field = "id, name";
        }else{
            $field = "id, name_hk as name";
        }
        $lists = Db::name("reg_type")
        ->field($field)
        ->select();

        $this->success("操作成功", $lists);
    }

    //获取行业列表
    public function getIndustryLists()
    {
        $lang = $this->request->post("lang", 1);
        if($lang == 1){
            $field = "id, name";
        }else{
            $field = "id, name_hk as name";
        }
        $lists = Db::name("industry")
        ->field($field)
        ->select();

        $this->success("操作成功", $lists);
    }

    //获取基金使用范围列表
    public function getPlanFundLists()
    {
        $lang = $this->request->post("lang", 1);
        if($lang == 1){
            $field = "id, name";
        }else{
            $field = "id, name_hk as name";
        }
        $lists = Db::name("plan_fund")
        ->field($field)
        ->select();

        $this->success("操作成功", $lists);
    }

    //申请香港移民
    public function applyMigrate()
    {
        $service_id = $this->request->post("service_id");
        $name = $this->request->post("name"); //申请人姓名
        $sex = $this->request->post("sex");  //1男   2女
        $marriage_type_id = $this->request->post("marriage_type_id"); //婚姻状态id
        $marriage_type_name = $this->request->post("marriage_type_name"); //婚姻状态名称
        $first_education_id = $this->request->post("first_education_id"); //最高学历id
        $first_education_name = $this->request->post("first_education_name"); //最高学历名称
        $collegeExamination = $this->request->post("collegeExamination"); //内地高考
        $ibdp = $this->request->post("ibdp"); //ibdp
        $hkdse = $this->request->post("hkdse"); //hkdse
        $ial = $this->request->post("ial"); //ial
        $other = $this->request->post("other"); //其他

        //验证数据不能为空
        if(empty($service_id)){
            $this->error("必要参数缺少");
        }

        $user = $this->auth->getUser();

        //插入数据
        Db::name("service_migrate_apply")
        ->insert([
            "uid" => $user->id,
            "service_id" => $service_id,
            "name" => $name,
            "sex" => $sex,
            "marriage_type_id" => $marriage_type_id,
            "marriage_type_name" => $marriage_type_name,
            "first_education_id" => $first_education_id,
            "first_education_name" => $first_education_name,
            "collegeExamination" => $collegeExamination,
            "ibdp" => $ibdp,
            "hkdse" => $hkdse,
            "ial" => $ial,
            "other" => $other,
            "createtime" => time()
        ]);

        $id = Db::name("service_migrate_apply")->getLastInsID();
        //插入订单表
        $params = [
            "service_id" => $service_id,
            "uid" => $user->id,
            "apply_name" => "migrate"
        ];
        $this->addServiceOrder($id, $params);

        $this->success("申请成功，请等待审核");

    }

    //获取婚姻状态列表
    public function getMarriageTypeLists()
    {
        $lang = $this->request->post("lang", 1);
        if($lang == 1){
            $field = "id, name";
        }else{
            $field = "id, name_hk as name";
        }
        $lists = Db::name("marriage_type")
        ->field($field)
        ->select();

        $this->success("操作成功", $lists);
    }

    //获取最高学历列表
    public function getEducationLists()
    {
        $lang = $this->request->post("lang", 1);
        if($lang == 1){
            $field = "id, name";
        }else{
            $field = "id, name_hk as name";
        }
        $lists = Db::name("Education")
        ->field($field)
        ->select();

        $this->success("操作成功", $lists);
    }

    //申请开办企业
    public function applyStartBusiness()
    {
        $service_id = $this->request->post("service_id");
        $business_name_cn = $this->request->post("business_name_cn"); //企业名称中文
        $business_name_en = $this->request->post("business_name_en");  //企业名称英文
        $holder_json = $this->request->post("holder_json"); //股东信息
        $holder_json = $this->htmlToJson($holder_json);
        $address_img = $this->request->post("address_img"); //地址证明（图片）
        $regist_money = $this->request->post("regist_money"); //注册资本（万元）
        $share_rate_json = $this->request->post("share_rate_json"); //股份比例
        $share_rate_json = $this->htmlToJson($share_rate_json);
        $regist_address = $this->request->post("regist_address"); //注册地址
        $business_scope = $this->request->post("business_scope"); //业务范围
        $legal_secretary_name = $this->request->post("legal_secretary_name"); //法定秘书姓名
        $legal_secretary_mobile = $this->request->post("legal_secretary_mobile"); //法定秘书手机号


        //验证数据不能为空
        if(empty($service_id)){
            $this->error("必要参数缺少");
        }

        $user = $this->auth->getUser();

        //插入数据
        Db::name("service_business_apply")
        ->insert([
            "uid" => $user->id,
            "service_id" => $service_id,
            "business_name_cn" => $business_name_cn,
            "business_name_en" => $business_name_en,
            "holder_json" => $holder_json,
            "address_img" => $address_img,
            "regist_money" => $regist_money,
            "share_rate_json" => $share_rate_json,
            "regist_address" => $regist_address,
            "business_scope" => $business_scope,
            "legal_secretary_name" => $legal_secretary_name,
            "legal_secretary_mobile" => $legal_secretary_mobile,
            "createtime" => time()
        ]);

        $id = Db::name("service_business_apply")->getLastInsID();
        //插入订单表
        $params = [
            "service_id" => $service_id,
            "uid" => $user->id,
            "apply_name" => "business"
        ];
        $this->addServiceOrder($id, $params);

        $this->success("申请成功，请等待审核");

    }


}
